/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assisisw.smartcal.webuisubsystem.managedbean.validator;

import assisisw.smartcal.entitysubsystem.IUserController;
import assisisw.smartcal.securitysubsystem.IMailVerifier;
import assisisw.smartcal.webuisubsystem.managedbean.DashboardBean;
import assisisw.smartcal.webuisubsystem.managedbean.calendar.EditCalendarControllerBean;
import java.io.Serializable;
import java.util.Objects;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import static javax.faces.context.FacesContext.getCurrentInstance;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

/**
 *
 * @author Francesco
 */
@ManagedBean
@Named ( "newSharingOnlyWithAlreadyRegisteredValidator" )
public class NewSharingOnlyWithAlreadyRegisteredValidator implements Validator , Serializable
{

    @EJB
    private IUserController userController ;
    
    @EJB
    private IMailVerifier mailVerifier ;
    
    /**
     * AS THE SUPER'S ONE.
     */
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
    {
        String mail ;
        if ( Objects.nonNull ( value ) && ! value.toString ().isEmpty () )
        {
            mail = value.toString () ;
            if ( ! ( mailVerifier.isStaticallyOk ( mail ) && mailVerifier.exists ( mail ) ) )
                throw new ValidatorException ( NewCalendarSharingValidator.MAIL_REQUIRED_MESSAGE ) ;
            else
            {
                if ( ! userController.isRegistered ( mail ) )
                    throw new ValidatorException ( new FacesMessage ( "User not registered in SmartCAL !" ) ) ;
                else
                    getCurrentInstance().getApplication().
                            evaluateExpressionGet(FacesContext.getCurrentInstance(), 
                "#{editCalendarControllerBean}",EditCalendarControllerBean.class).setNewSharedMailValid();
            }
        }
        else
            throw new ValidatorException ( new FacesMessage ( "Required !" ) ) ;
    }
    
}
